
package com.rt.schedulenew.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.rt.schedulebase.dto.*;
import com.rt.schedulebase.entity.*;
import com.rt.schedulebase.entity.commonentity.PageResultUtil;
import com.rt.schedulebase.mapper.DictScheduleApmMapper;
import com.rt.schedulebase.mapper.ExamApplyMapper;
import com.rt.schedulebase.mapper.ExamApplyPatientMapper;
import com.rt.schedulebase.mapper.ExamScheduleActMapper;
import com.rt.schedulenew.api.*;
import com.rt.schedulenew.utils.base.BigDecimalUtil;
import com.rt.schedulenew.utils.base.CommonUtil;
import com.rt.schedulenew.utils.base.ConstantsUtil;
import com.rt.schedulenew.utils.global.ErrorCode;
import com.rt.schedulenew.utils.global.JsonResult;
import com.rt.schedulenew.utils.global.JsonResultUtil;
import com.rt.schedulenew.utils.util.DateUtil;
import com.rt.schedulenew.utils.util.HttpUtil;
import com.rt.schedulenew.utils.util.JsonUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class ExamApplyPatientServiceImpl extends ServiceImpl<ExamApplyPatientMapper, ExamApplyPatient> implements IExamApplyPatientService {
    private static Logger logger = LoggerFactory.getLogger(ExamApplyPatientServiceImpl.class);
    @Autowired
    private ExamApplyMapper examApplyMapper;
    @Autowired
    private ExamScheduleActMapper examScheduleActMapper;
    @Autowired
    private ICommonService commonServiceImpl;
    @Autowired
    private ConfigServiceImpl configServiceImpl;
    @Autowired
    private DictScheduleApmMapper dictScheduleApmMapper;
    @Autowired
    private IDictExamClassService dictExamClassService;
    @Autowired
    private IDictTerminalService dictTerminalService;
    @Autowired
    private IExamApplyPatientIdService idService;
    @Autowired
    private IDictHospitalService dictHospitalService;
    @Autowired
    private IDictExamZoneService dictExamZoneService;

    public JsonResult getPatientListOut(ExamApplyDto dto) {
        configServiceImpl.toUpperCaseInput(dto);
        if (StringUtils.isNotBlank(dto.getIcCard())) {
            String configStr = configServiceImpl.getConfigByName(ConstantsUtil.ConfigName.IS_GET_REFER_PATIENT_INFO.getKey());
            if (StringUtils.isNotBlank(configStr)) {
                ConfigDto.GetReferPatientInfo configInfo = JsonUtil.toBean(configStr, ConfigDto.GetReferPatientInfo.class);
                if (configInfo != null && "0".equals(configInfo.getGrant()) && StringUtils.isNotBlank(configInfo.getGetReferPatientInfoUrl())) {
                    String url = configInfo.getGetReferPatientInfoUrl();
                    ExamApplyDto examApplyDto = new ExamApplyDto();
                    examApplyDto.setIcCard(dto.getIcCard());
                    String bodyContent = JsonUtil.toJson(examApplyDto);
                    logger.info("----------------调用第三方获取患者信息接口(请求地址:{},请求内容:{})-------------------", url, bodyContent);
                    HttpUtil httpUtil = new HttpUtil();
                    String result = httpUtil.sendHttpPostBody(url, bodyContent);
                    logger.info("----------------调用第三方获取患者信息接口(响应内容:{})-------------------", result);
                    if (StringUtils.isNotBlank(result)) {
                        JsonResult jsonResult = JsonUtil.toBean(result, JsonResult.class);
                        if ("0".equals(jsonResult.getStatus())) {
                            Map<String, Object> resultMap = JsonResultUtil.getResult(jsonResult);
                            if (resultMap.get("icCard") != null) {
                                dto.setIcCard((String) resultMap.get("icCard"));
                            }
                            if (resultMap.get("sickId") != null) {
                                dto.setSickId((String) resultMap.get("sickId"));
                            }
                            if (resultMap.get("name") != null) {
                                dto.setName((String) resultMap.get("name"));
                            }
                            if (resultMap.get("age") != null) {
                                dto.setAge((String) resultMap.get("age"));
                            }
                            if (resultMap.get("sex") != null) {
                                dto.setSex((String) resultMap.get("sex"));
                            }
                            if (resultMap.get("birthDate") != null) {
                                dto.setBirthDate((String) resultMap.get("birthDate"));
                            }
                            if (resultMap.get("phoneNumber") != null) {
                                dto.setPhoneNumber((String) resultMap.get("phoneNumber"));
                            }
                        }
                    }
                    List<ExamApplyDto> lsExamApplyDto = new ArrayList<ExamApplyDto>();
                    lsExamApplyDto.add(dto);
                    return JsonResultUtil.success(lsExamApplyDto);
                }
            }
        }
        String configStr = configServiceImpl.getConfigByName(ConstantsUtil.ConfigName.IS_VIRTUAL_CARD_READER.getKey());
        if ("2".equals(configStr)) {
            String configUrl = configServiceImpl.getConfigByName(ConstantsUtil.ConfigName.VIRTUAL_CARD_READER_URL.getKey());
            if (StringUtils.isNotBlank(configUrl)) {
                ExamApplyDto examApplyDto2 = new ExamApplyDto();
                examApplyDto2.setCardNo(dto.getCommonCard());
                String bodyContent2 = JsonUtil.toJson(examApplyDto2);
                logger.info("----------------调用第三方卡号转换接口(请求地址:{},请求内容:{})-------------------", configUrl, bodyContent2);
                HttpUtil httpUtil2 = new HttpUtil();
                String result2 = httpUtil2.sendHttpPostBody(configUrl, bodyContent2);
                logger.info("----------------调用第三方卡号转换接口(响应内容:{})-------------------", result2);
                if (StringUtils.isNotBlank(result2)) {
                    Map<String, Object> resultMap2 = JsonUtil.json2Map(result2);
                    if ("0".equals(resultMap2.get("status")) && StringUtils.isNotBlank(String.valueOf(resultMap2.get("cardNo")))) {
                        dto.setCommonCard((String) resultMap2.get("cardNo"));
                    }
                }
            }
        }
        dto.setCommonCard(configServiceImpl.icCardPre(dto.getCommonCard()));
        dto.setExamClasses(CommonUtil.split2List(dto.getExamClass()));
        dto.setPatientSources(CommonUtil.split2List(dto.getPatientSource()));
        dto.setApplyNos(CommonUtil.split2List(dto.getApplyNo()));
        dto.setPriorityOrders(CommonUtil.split2List(dto.getPriorityOrder()));
        dto.setPriorityOrder(null);
        dto.setReqWardCodes(CommonUtil.split2List(dto.getReqWardCode()));
        dto.setReqWardCode(null);
        dto.setReqDepts(CommonUtil.split2List(dto.getDeptCode()));
        dto.setPerformDepts(CommonUtil.split2List(dto.getPerformDept()));
        dto.setPerformDept(null);
        dto.setItemFlags(CommonUtil.convertItemFlagsCondition(dto.getItemFlags()));
        dto.setScheduleStatus(CommonUtil.convertScheduleStatus(dto.getScheduleStatus()));
        if (StringUtils.isNotBlank(dto.getItemStatus())) {
            dto.setScheduleStatus(CommonUtil.convertScheduleStatus(dto.getItemStatus()));
        }
        dto.setIncludeFlags(CommonUtil.convertFlagsCondition(dto.getIncludeFlags()));
        List<String> excludeFlagsList = new ArrayList<String>();
        List<String> flagList = CommonUtil.split2List(dto.getExcludeFlags());
        for (String flag : flagList) {
            excludeFlagsList.add(CommonUtil.convertFlagsCondition(flag));
        }
        dto.setExcludeFlagsList(excludeFlagsList);
        dto.setExcludeFlags(null);
        if (StringUtils.isNotBlank(dto.getIcCard2()) || StringUtils.isNotBlank(dto.getIcCard()) || StringUtils.isNotBlank(dto.getSickId()) || StringUtils.isNotBlank(dto.getOutpatientNo()) || StringUtils.isNotBlank(dto.getApplyNo()) || StringUtils.isNotBlank(dto.getCommonCard())) {
            commonServiceImpl.getHisApplyByThirdUrl(dto);
        }
        int pageNo = 1;
        int pageSize = 100;
        List<String> sickIdList = configServiceImpl.getInputNewSupport(dto);
        dto.setSickIds(sickIdList);
        PageHelper.startPage(pageNo, pageSize);
        List<ExamApplyDto> list = examApplyMapper.getPatientListOut(dto);
        if (CollectionUtils.isNotEmpty(list)) {
            List<String> sickList = list.stream().map(ead -> ead.getSickId())
                    .collect(Collectors.toList());

            List<ExamApplyDto> lsExamApply = new ArrayList<>();
            if (CollectionUtils.isNotEmpty(sickList)) {
                dto.setSickIds(sickList);
                lsExamApply = examApplyMapper.getScheduleList(dto);
            }
            Map<String, String> scheduleStatusMap = new HashMap<>();
            for (ExamApplyDto ea : lsExamApply) {
                String sickName = ea.getSickId() + ea.getName();
                String scheduleStatus = (ea.getExamStatus() != null) ? ea.getExamStatus() : ea.getScheduleStatus();
                if (ConstantsUtil.ScheduleStatus.ONE.getStatus().equals(scheduleStatus)) {
                    scheduleStatus = null;
                }
                if (!scheduleStatusMap.containsKey(sickName) && StringUtils.isBlank(scheduleStatus)) {
                    scheduleStatusMap.put(sickName, ConstantsUtil.ScheduleStatus.ZERO.getStatus());
                }
            }
            for (ExamApplyDto eadItem : list) {
                String sickName = eadItem.getSickId() + eadItem.getName();
                if (scheduleStatusMap.containsKey(sickName)) {
                    eadItem.setScheduleStatus("0");
                } else {
                    eadItem.setScheduleStatus("1");
                }
            }
        }
        return JsonResultUtil.success(list);
    }

    /***
     * 获取患者信息列表
     * @param dto
     * @param showDetails
     * @return
     */
    @Override
    public JsonResult getPatientList(ExamApplyDto dto, boolean showDetails) {
        configServiceImpl.toUpperCaseInput(dto);

        String configStr = configServiceImpl.getConfigByName(ConstantsUtil.ConfigName.IS_VIRTUAL_CARD_READER.getKey());
        if ("2".equals(configStr)) {
            String configUrl = configServiceImpl.getConfigByName(ConstantsUtil.ConfigName.VIRTUAL_CARD_READER_URL.getKey());
            if (StringUtils.isNotBlank(configUrl)) {
                ExamApplyDto examApplyDto = new ExamApplyDto();
                examApplyDto.setCardNo(dto.getCommonCard());
                String bodyContent = JsonUtil.toJson(examApplyDto);
                logger.info("----------------调用第三方卡号转换接口(请求地址:{},请求内容:{})-------------------", configUrl, bodyContent);
                HttpUtil httpUtil = new HttpUtil();
                String result = httpUtil.sendHttpPostBody(configUrl, bodyContent);
                logger.info("----------------调用第三方卡号转换接口(响应内容:{})-------------------", result);
                if (StringUtils.isNotBlank(result)) {
                    Map<String, Object> resultMap = JsonUtil.json2Map(result);
                    if ("0".equals(resultMap.get("status")) && StringUtils.isNotBlank(String.valueOf(resultMap.get("cardNo")))) {
                        dto.setCommonCard((String) resultMap.get("cardNo"));
                    }
                }
            }
        }
        // 综合号码-增加前缀
        dto.setCommonCard(configServiceImpl.icCardPre(dto.getCommonCard()));
        dto.setExamClasses(CommonUtil.split2List(dto.getExamClass()));
        dto.setPatientSources(CommonUtil.split2List(dto.getPatientSource()));
        dto.setApplyNos(CommonUtil.split2List(dto.getApplyNo()));
        dto.setPriorityOrders(CommonUtil.split2List(dto.getPriorityOrder()));
        dto.setPriorityOrder(null);
        dto.setReqWardCodes(CommonUtil.split2List(dto.getReqWardCode()));
        dto.setReqWardCode(null);
        dto.setReqDepts(CommonUtil.split2List(dto.getDeptCode()));
        dto.setPerformDepts(CommonUtil.split2List(dto.getPerformDept()));
        dto.setPerformDept(null);
        dto.setItemFlags(CommonUtil.convertItemFlagsCondition(dto.getItemFlags()));
        dto.setScheduleStatus(CommonUtil.convertScheduleStatus(dto.getScheduleStatus()));
        if (StringUtils.isNotBlank(dto.getItemStatus())) {
            dto.setScheduleStatus(CommonUtil.convertScheduleStatus(dto.getItemStatus()));
        }
        dto.setIncludeFlags(CommonUtil.convertFlagsCondition(dto.getIncludeFlags()));
        List<String> excludeFlagsList = new ArrayList<>();
        List<String> flagList = CommonUtil.split2List(dto.getExcludeFlags());
        for (String flag : flagList) {
            excludeFlagsList.add(CommonUtil.convertFlagsCondition(flag));
        }
        dto.setExcludeFlagsList(excludeFlagsList);
        dto.setExcludeFlags(null);
        if (StringUtils.isNotBlank(dto.getIcCard2())
                || StringUtils.isNotBlank(dto.getIcCard())
                || StringUtils.isNotBlank(dto.getSickId())
                || StringUtils.isNotBlank(dto.getOutpatientNo())
                || StringUtils.isNotBlank(dto.getApplyNo()) || StringUtils.isNotBlank(dto.getCommonCard())) {

            commonServiceImpl.getHisApplyByThirdUrl(dto);
        }
        Page<ExamApplyDto> page = new Page<>();
        int pageNo = (dto.getPageNo() != null) ? dto.getPageNo() : 1;
        int pageSize = (dto.getPageSize() != null) ? dto.getPageSize() : 100;
        // 从传入参数里面获取到患者id列表
        List<String> sickIdList = configServiceImpl.getInputNewSupport(dto);
        List<ExamApplyDto> list = new ArrayList<>();
        // 通用诊疗卡
        if (StringUtils.isNotBlank(dto.getCommonCard())) {
            List<String> sickIds = commonServiceImpl.getSickIds(dto);
            if (CollectionUtils.isNotEmpty(sickIds)) {
                dto.setSickIds(sickIds);
                page = PageHelper.startPage(pageNo, pageSize);
                if (showDetails) {
                    list = examApplyMapper.getPatientInfoList(dto);
                } else {
                    list = examApplyMapper.getPatientList(dto);
                }
            }
        } else {
            dto.setSickIds(sickIdList);
            page = PageHelper.startPage(pageNo, pageSize);
            if (showDetails) {
                list = examApplyMapper.getPatientInfoList(dto);
            } else {
                list = examApplyMapper.getPatientList(dto);
            }
        }
        List<String> sickList = list.stream().map(ead->ead.getSickId())
                .collect(Collectors.toList());
        // 获取患者的申请单信息
        List<ExamApplyDto> lsExamApply = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(sickList)) {
            dto.setSickIds(sickList);
            lsExamApply = examApplyMapper.getScheduleList(dto);
        }

        // 没有预约的申请单加到里面
        Map<String, String> examApplyMap = new HashMap<>();
        for (ExamApplyDto ea : lsExamApply) {
            // 患者key
            String sickName = ea.getSickId() + ea.getName();

            String scheduleStatus = (ea.getExamStatus() != null) ? ea.getExamStatus() : ea.getScheduleStatus();
            if (ConstantsUtil.ScheduleStatus.ONE.getStatus().equals(scheduleStatus)) {
                scheduleStatus = null;
            }

            if (StringUtils.isNotBlank(ea.getBedNo())) {
                String sickName_bedNo = sickName + "_bedNo";
                if (!examApplyMap.containsKey(sickName_bedNo)) {
                    examApplyMap.put(sickName_bedNo, ea.getBedNo());
                }
            }
            String sickName_reqDate = sickName + "_reqDate";
            if (!examApplyMap.containsKey(sickName_reqDate)) {
                examApplyMap.put(sickName_reqDate, ea.getReqDate());
            }
            String sickName_visitDate = sickName + "_visitDate";
            if (!examApplyMap.containsKey(sickName_visitDate)) {
                examApplyMap.put(sickName_visitDate, ea.getVisitDate());
            }
            String sickName_scheduleDate = sickName + "_scheduleDate";
            if (!examApplyMap.containsKey(sickName_scheduleDate)) {
                examApplyMap.put(sickName_scheduleDate, ea.getScheduleDate());
            }
            String sickName_scheduledTime = sickName + "_scheduledTime";
            if (!examApplyMap.containsKey(sickName_scheduledTime)) {
                examApplyMap.put(sickName_scheduledTime, ea.getScheduledTime());
            }
            // 如果都没有 就是未预约状态
            if (!examApplyMap.containsKey(sickName) && StringUtils.isBlank(scheduleStatus)) {
                examApplyMap.put(sickName, ConstantsUtil.ScheduleStatus.ZERO.getStatus());
            }
        }
        // 构建最后的返回数据
        for (ExamApplyDto ead2 : list) {
            String sickName = ead2.getSickId() + ead2.getName();
            if (examApplyMap.containsKey(sickName)) {
                ead2.setScheduleStatus("0");
            } else {
                ead2.setScheduleStatus("1");
            }
            String sickName_bedNo2 = sickName + "_bedNo";
            if (examApplyMap.containsKey(sickName_bedNo2)) {
                ead2.setBedNo(examApplyMap.get(sickName_bedNo2));
            }
            String sickName_reqDate = sickName + "_reqDate";
            if (examApplyMap.containsKey(sickName_reqDate)) {
                ead2.setReqDate(examApplyMap.get(sickName_reqDate));
            }
            String sickName_visitDate = sickName + "_visitDate";
            if (examApplyMap.containsKey(sickName_visitDate)) {
                ead2.setVisitDate(examApplyMap.get(sickName_visitDate));
            }
            String sickName_scheduleDate = sickName + "_scheduleDate";
            if (examApplyMap.containsKey(sickName_scheduleDate)) {
                ead2.setScheduleDate(examApplyMap.get(sickName_scheduleDate));
            }
            String sickName_scheduledTime = sickName + "_scheduledTime";
            if (examApplyMap.containsKey(sickName_scheduledTime)) {
                ead2.setScheduledTime(examApplyMap.get(sickName_scheduledTime));
            }
        }
//        String sortSetConfigName = ConstantsUtil.ConfigName.CUSTOM_TABLE_ROW_SORT_SET_BY_SCHEDULE_SIGN_PATIENT_LIST.key;
//        if (StringUtils.isNotBlank(dto.getTerminalType()) && (ConstantsUtil.TerminalType.CLINIC_IN.getType().equals(dto.getTerminalType()) || ConstantsUtil.TerminalType.CLINIC_OUT.getType().equals(dto.getTerminalType()))) {
//            sortSetConfigName = ConstantsUtil.ConfigName.CUSTOM_TABLE_ROW_SORT_SET_BY_CLINICSCHE_PATIENT_LIST.key;
//        }
//        String sortSetStr = configServiceImpl.getConfigByName(sortSetConfigName);
//        ConfigDto.SortSet sortSet = null;
//        if (StringUtils.isNotBlank(sortSetStr)) {
//            sortSet = JsonUtil.json2Bean(sortSetStr, ConfigDto.SortSet.class);
//        }
        // 以自定义排序规则进行排序
        commonServiceImpl.customSort(list, dto.getTerminalType());
        return PageResultUtil.success(ErrorCode.SUCCESS.getValue(), list, page);
    }

    /**
     * 获取患者申请单列表和状态
     *
     * @param dto
     * @return
     */
    @Override
    public JsonResult getPatientApplyList(ExamApplyDto dto) {
        if (StringUtils.isBlank(dto.getName())
                && StringUtils.isBlank(dto.getIcCard())
                && StringUtils.isBlank(dto.getSickId())
                && StringUtils.isBlank(dto.getCommonCard())
                && StringUtils.isBlank(dto.getApplyNo())) {
            return JsonResultUtil.failure("健康卡号不能为空");
        }

        configServiceImpl.toUpperCaseInput(dto);
        // 对卡号进行转换，返回院内能识别的卡号
        String configStr = configServiceImpl.getConfigByName(ConstantsUtil.ConfigName.IS_VIRTUAL_CARD_READER.getKey());
        if ("2".equals(configStr)) {
            String configUrl = configServiceImpl.getConfigByName(ConstantsUtil.ConfigName.VIRTUAL_CARD_READER_URL.getKey());
            if (StringUtils.isNotBlank(configUrl)) {
                ExamApplyDto examApplyDto = new ExamApplyDto();
                examApplyDto.setCardNo(dto.getCommonCard());
                String bodyContent = JsonUtil.toJson(examApplyDto);
                logger.info("----------------调用第三方卡号转换接口(请求地址:{},请求内容:{})-------------------", configUrl, bodyContent);
                HttpUtil httpUtil = new HttpUtil();
                String result = httpUtil.sendHttpPostBody(configUrl, bodyContent);
                logger.info("----------------调用第三方卡号转换接口(响应内容:{})-------------------", result);
                if (StringUtils.isNotBlank(result)) {
                    Map<String, Object> resultMap = JsonUtil.json2Map(result);
                    if ("0".equals(resultMap.get("status")) && StringUtils.isNotBlank(String.valueOf(resultMap.get("cardNo")))) {
                        dto.setCommonCard((String) resultMap.get("cardNo"));
                    }
                }
            }
        }
        dto.setCommonCard(configServiceImpl.icCardPre(dto.getCommonCard()));
        String unSchedulePatientSource = null;
        if (StringUtils.isNotBlank(dto.getTerminalType()) && ConstantsUtil.TerminalType.SELF.getType().equals(dto.getTerminalType()) && StringUtils.isNotBlank(dto.getDeviceId())) {
            DictTerminalDto dictTerminalDto = new DictTerminalDto();
            dictTerminalDto.setIpAddress(dto.getDeviceId());
            DictTerminalDto terminalDto = dictTerminalService.getSelfDeviceInfo(dictTerminalDto);
            if (terminalDto == null) {
                return JsonResultUtil.failure("自助机配置信息不存在");
            }
            unSchedulePatientSource = terminalDto.getUnSchedulePatientSource();
            dto.setUnSchedulePatientSources(CommonUtil.split2List(unSchedulePatientSource));
            if (StringUtils.isNotBlank(terminalDto.getScheduleExamClass())) {
                dto.setExamClass(terminalDto.getScheduleExamClass());
            }
        }
        dto.setExamClasses(dictExamClassService.getExamClass(dto.getExamClass()));
        String customDeptCode = configServiceImpl.getConfigByName(ConstantsUtil.ConfigName.CUSTOM_DEPT_CODE.getKey());
        if (StringUtils.isNotBlank(customDeptCode)) {
            dto.setPerformDepts(CommonUtil.split2List(customDeptCode));
        }
        dto.setNotExamClasses(configServiceImpl.getNotExamClassList());
        dto.setReqDepts(CommonUtil.split2List(dto.getDeptCode()));
        dto.setPatientSources(CommonUtil.split2List(dto.getPatientSource()));
        dto.setApplyNos(CommonUtil.split2List(dto.getApplyNo()));
        dto.setApplyNo(null);
        dto.setPriorityOrders(CommonUtil.split2List(dto.getPriorityOrder()));
        dto.setPriorityOrder(null);
        dto.setReqWardCodes(CommonUtil.split2List(dto.getReqWardCode()));
        dto.setReqWardCode(null);
        dto.setPerformDepts(CommonUtil.split2List(dto.getPerformDept()));
        dto.setPerformDept(null);
        List<String> sickIdList = configServiceImpl.getInputNewSupport(dto);
        if (StringUtils.isNotBlank(dto.getCommonCard()) && !"0".equals(dto.getCommonCard())) {
            List<String> sickIds = commonServiceImpl.getSickIds(dto);
            if (sickIds.size() == 0) {
                String strReturn = "您的检查申请单信息不存在，如有疑问请到护士站咨询";
                String reminder = configServiceImpl.customReminder(ConstantsUtil.ConfigName.NO_QUERY_EXAM_APPLY_REMINDER.getKey(), "", "");
                if (StringUtils.isNotBlank(reminder)) {
                    strReturn = reminder;
                }
                return JsonResultUtil.failure(strReturn);
            }
            dto.setSickIds(sickIds);
        } else {
            dto.setSickIds(sickIdList);
        }
        dto.setItemFlags(CommonUtil.convertItemFlagsCondition(dto.getItemFlags()));
        dto.setScheduleStatus(CommonUtil.convertScheduleStatus(dto.getScheduleStatus()));
        // 获取申请列表信息
        List<ExamApplyDto> lsExamApplyDto = examApplyMapper.getList(dto);

        List<DictExamClass> examClassList = dictExamClassService.getListAll();
        if (!CollectionUtils.isEmpty(examClassList)) {
            List<String> examNameList = examClassList.stream().map(DictExamClass::getExamClassName).collect(Collectors.toList());
            // 移除没有在检查类别表里面的申请单项目
            lsExamApplyDto.removeIf(ea -> !examNameList.contains(ea.getExamClass()));
        }

//         if (ConstantsUtil.TerminalType.MOBILE.getType().equals(dto.getTerminalType())) {
//             commonServiceImpl.mobileConfigCorrelation(lsExamApplyDto, dto);
//         }
        // 判断终端的申请时间限制
        lsExamApplyDto.removeIf(ea -> configServiceImpl.isApplyDateLimit(dto.getTerminalType(), ea.getExamClass(), ea.getReqDate()));
        // 设置缴费状态
        for (ExamApplyDto ea2 : lsExamApplyDto) {
            ea2.setChargeFlag(commonServiceImpl.getChargeFlag(ea2));
        }
        // 合并申请单-如果有合并的申请单挂载到同一条记录
        lsExamApplyDto = commonServiceImpl.mergeApply(lsExamApplyDto, dto.getHistoryFlag(), dto.getTerminalType(), dto.getIsMergeChannel());

        // 合单结果为空-说明没有可以操作的申请单
        if (CollectionUtils.isEmpty(lsExamApplyDto)) {
            String desc = "您还没有" + (StringUtils.isBlank(dto.getExamClass()) ? "" : dto.getExamClass()) + "检查申请单信息，如有疑问请到护士站咨询!";
            String reminder = configServiceImpl.customReminder(ConstantsUtil.ConfigName.NO_QUERY_EXAM_APPLY_REMINDER.getKey(), "", dto.getExamClass());
            if (StringUtils.isNotBlank(reminder)) {
                desc = reminder;
            }
//            if (ConstantsUtil.TerminalType.SELF.getType()
//                    .equals(dto.getTerminalType())
//                    && CollectionUtils.isEmpty(dto.getUnSchedulePatientSources())) {
//                desc = "该自助终端暂不支持" + (StringUtils.isNotBlank(unSchedulePatientSource) ? unSchedulePatientSource : "") + "患者预约，如有疑问请到护士站咨询";
//            }
            return JsonResultUtil.failure(desc);
        }
        if (StringUtils.isNotBlank(dto.getItemStatus())) {
            lsExamApplyDto
                    .removeIf(ea -> !dto.getItemStatus().equals("1".equals(ea.getScheduleStatus()) ? "0" : ea.getScheduleStatus()));
        }
        // 操作人员信息
        DictUsersDto dictUsers = commonServiceImpl.dictUsers(dto);
        for (ExamApplyDto applyDto : lsExamApplyDto) {
            applyDto.setGestational("0");
            applyDto.setLastMensesDate("");
            if (applyDto.getSex() != null && applyDto.getSex().contains(ConstantsUtil.Gender.WOMAN.getValue())) {
                List<ExamApplyItemDto> gestationalItems = commonServiceImpl.getGestationalItems(applyDto.getItems());
                if (gestationalItems.size() > 0) {
                    String isGestational = "1";
                    String lastMensesDateStr = applyDto.getLastMensesDate();
                    if (StringUtils.isBlank(lastMensesDateStr)) {
                        lastMensesDateStr = commonServiceImpl.getLastMensesDate(applyDto.getSickId());
                    }
                    if (StringUtils.isNotBlank(lastMensesDateStr)) {
                        Date nowDate = DateUtil.getNow();
                        Date lastMensesDate = DateUtil.parse(lastMensesDateStr, DateUtil.FORMAT_DATE);
                        int allDays = (int) ((nowDate.getTime() - lastMensesDate.getTime()) / 86400000L);
                        int weeks = allDays / 7;
                        if (weeks < 50) {
                            isGestational = "2";
                        }
                    }
                    applyDto.setGestational(isGestational);
                    applyDto.setLastMensesDate(lastMensesDateStr);
                }
            }
            // 需默认镇静的年龄与项目
            configServiceImpl.IsNeedClamAgeByItem(applyDto);

            String isScheduleHint = commonServiceImpl.isScheduleByFlags(applyDto.getItems(), dto.getTerminalType(), applyDto.getChargeType());
            applyDto.setOnlyDeptscheScheduleHint(isScheduleHint);
            if (StringUtils.isNotBlank(applyDto.getScheduledId())) {
                applyDto.setBPrintType("1");
                applyDto.setPrintType("1");

                // 查找申请单预约操作的打印历史
                ExamScheduleActDto actDto = new ExamScheduleActDto();
                actDto.setScheduledId(applyDto.getScheduledId());
                actDto.setActType(ConstantsUtil.ActType.SCHE_PRINT.getType());
                List<ExamScheduleActDto> actList = examScheduleActMapper.getExamScheduleActList(actDto);

                // 查找打印状态 todo 可优化 每次查询操作记录表太费数据库资源
                if (CollectionUtils.isNotEmpty(actList)) {
                    for (ExamScheduleActDto examScheduleAct : actList) {
                        List<String> clinicTerminal = Arrays.asList(ConstantsUtil.TerminalType.CLINIC_IN.getType(), ConstantsUtil.TerminalType.CLINIC_OUT.getType());
                        if (clinicTerminal.contains(examScheduleAct.getTerminalType())) {
                            applyDto.setBPrintType("2");
                        } else {
                            applyDto.setPrintType("2");
                        }
                    }
                }
            }
        }
        // 根据 推荐同天还是 最早 进行预约操作
        commonServiceImpl.getSchedulePlans(lsExamApplyDto, dictUsers, dto.getPlanMode(), dto.getTerminalType(), dto.getHospitalCode());

//        String sortSetConfigName = ConstantsUtil.ConfigName.CUSTOM_TABLE_ROW_SORT_SET_BY_SCHEDULE_SIGN.key;
//        if (StringUtils.isNotBlank(dto.getTerminalType()) && (ConstantsUtil.TerminalType.CLINIC_IN.getType().equals(dto.getTerminalType()) || ConstantsUtil.TerminalType.CLINIC_OUT.getType().equals(dto.getTerminalType()))) {
//            sortSetConfigName = ConstantsUtil.ConfigName.CUSTOM_TABLE_ROW_SORT_SET_BY_CLINICSCHE.key;
//        }
//        String sortSetStr = configServiceImpl.getConfigByName(sortSetConfigName);
//        ConfigDto.SortSet sortSet = null;
//        if (StringUtils.isNotBlank(sortSetStr)) {
//            sortSet = JsonUtil.json2Bean(sortSetStr, ConfigDto.SortSet.class);
//        }
        // 自定义排序规则
        commonServiceImpl.customSort(lsExamApplyDto, dto.getTerminalType());
        return JsonResultUtil.success("成功", lsExamApplyDto);
    }

    @Override
    public JsonResult getPatientInfo(ExamApplyPatientDto dto) {
        if (StringUtils.isBlank(dto.getSickId()) && StringUtils.isBlank(dto.getIcCard()) && StringUtils.isBlank(dto.getCommonCard())) {
            return JsonResultUtil.failure("病人ID和IC卡号不能同时为空");
        }
        configServiceImpl.toUpperCaseInput(dto);
        dto.setCommonCard(configServiceImpl.icCardPre(dto.getCommonCard()));
        if (((ConstantsUtil.TerminalType.SELF.getType().equals(dto.getTerminalType()) || ConstantsUtil.TerminalType.MOBILE.getType().equals(dto.getTerminalType()) || ConstantsUtil.TerminalType.CLINIC_IN.getType().equals(dto.getTerminalType())) && StringUtils.isNotBlank(dto.getIcCard2())) || StringUtils.isNotBlank(dto.getIcCard()) || StringUtils.isNotBlank(dto.getSickId()) || StringUtils.isNotBlank(dto.getOutpatientNo()) || StringUtils.isNotBlank(dto.getApplyNo()) || StringUtils.isNotBlank(dto.getCommonCard())) {
            ExamApplyDto examApplyCp = new ExamApplyDto();
            BeanUtils.copyProperties(dto, examApplyCp);
            commonServiceImpl.getHisApplyByThirdUrl(examApplyCp);
        }
        if (StringUtils.isNotBlank(dto.getSickId())) {
            dto.setCommonCard(null);
        } else {
            String inputSupport = configServiceImpl.getIcCardInputSupport();
            if (inputSupport.contains("ic_card")) {
                dto.setSupportByIcCard("1");
            }
            if (inputSupport.contains("inpatient_no")) {
                dto.setSupportByInpatientNo("1");
            }
            if (inputSupport.contains("outpatient_no")) {
                dto.setSupportByOutpatientNo("1");
            }
            if (inputSupport.contains("identity_card")) {
                dto.setSupportByIdentityCard("1");
            }
            if (inputSupport.contains("mi_card")) {
                dto.setSupportByMiCard("1");
            }
            if (inputSupport.contains("sick_id")) {
                dto.setSupportBySickId("1");
            }
            if (inputSupport.contains("apply_no")) {
                dto.setSupportByApplyNo("1");
            }
            if (inputSupport.contains("health_card")) {
                dto.setSupportByHealthCard("1");
            }
            if (inputSupport.contains("out_reg_no")) {
                dto.setSupportByOutRegNo("1");
            }
        }
        dto.setExamClasses(CommonUtil.split2List(dto.getExamClass()));
        ExamApplyPatientDto patientInfo = null;
        if (ConstantsUtil.TerminalType.SELF.getType().equals(dto.getTerminalType())
                || ConstantsUtil.TerminalType.MOBILE.getType().equals(dto.getTerminalType())) {

            // 获取申请患者列表
            List<ExamApplyPatientDto> examApplyPatientDtoList = examApplyMapper.getPatientInfo2(dto);
            if (examApplyPatientDtoList != null && !examApplyPatientDtoList.isEmpty()) {
                List<String> phoneNumberList = new ArrayList<String>();
                for (ExamApplyPatientDto examApplyPatientDto : examApplyPatientDtoList) {
                    if (StringUtils.isNotBlank(examApplyPatientDto.getPhoneNumber())
                            && !phoneNumberList.contains(examApplyPatientDto.getPhoneNumber())) {
                        phoneNumberList.add(examApplyPatientDto.getPhoneNumber());
                    }
                }
                patientInfo = examApplyPatientDtoList.get(0);
                patientInfo.setPhoneNumbers(phoneNumberList);
            }
        } else {
            patientInfo = examApplyMapper.getPatientInfo(dto);
        }
        if (ConstantsUtil.TerminalType.MOBILE.getType().equals(dto.getTerminalType()) && patientInfo != null) {
            ExamApplyPatientIdDto examApplyPatientId = new ExamApplyPatientIdDto();
            examApplyPatientId.setSickId(patientInfo.getSickId());
            examApplyPatientId.setDomainId("0007");
            List<ExamApplyPatientId> ids = idService.selectd(examApplyPatientId);
            if (!ids.isEmpty()) {
                patientInfo.setIcCard(StringUtils.isNotBlank(ids.get(0).getPatientId()) ? ids.get(0).getPatientId() : patientInfo.getIcCard());
            }
        }
        if (patientInfo != null && ConstantsUtil.TerminalType.DEPT.getType().equals(dto.getTerminalType())) {
            String accountBalance = configServiceImpl.getAccountBalance(patientInfo);
            patientInfo.setAccountBalance(accountBalance);
        }
        if (patientInfo == null) {
            String desc = "没有查询到您的" + (StringUtils.isBlank(dto.getExamClass()) ? "" : dto.getExamClass()) + "检查申请,如有疑问请到护士站咨询!";
            return JsonResultUtil.failure(desc);
        }
        return JsonResultUtil.success("成功", patientInfo);
    }

    @Override
    public JsonResult getExamApplyInfo(ExamApplyDto dto) {
        if (StringUtils.isBlank(dto.getApplyNo())) {
            return JsonResultUtil.failure("申请单号不能为空!");
        }
        // 获取申请单信息
        ExamApplyDto ea = commonServiceImpl.getExamApplyInfo(dto.getApplyNo(), dto.getTerminalType());
        // 获取申请单项目列表信息
        List<ExamApplyItemDto> applyItemDtos = commonServiceImpl.getExamApplyItem(dto.getMergeNo(), ea);
        // 查询类型
        String type = "SIGN".equals(dto.getType()) ? ConstantsUtil.ReminderType.SIGN.getType() : ConstantsUtil.ReminderType.SCHEDULE.getType();
        List<String> reminders = getReminders(type, ea.getExamClass(), dto.getTerminalType());
        // 组装预约信息
        ExamApplyDto apply = getApplyForScheduleInfo(dto, ea, applyItemDtos);

        apply.setReminders(CommonUtil.convertNotice(reminders, ea.getPatientSource(), null, ea.getBirthDate()));
        apply.setMemo(ea.getMemo());
        apply.setChargeFlag(ea.getChargeFlag());
        List<String> applyNoList = CommonUtil.mergeNo2ApplyNos(dto.getMergeNo());
        if (applyNoList.size() > 1) {
            List<String> reqMemoList = new ArrayList<>();
            if (StringUtils.isNotBlank(ea.getReqMemo())) {
                reqMemoList.add(ea.getReqMemo());
            }
            for (String applyNo : applyNoList) {
                if (applyNo.equals(dto.getApplyNo())) {
                    continue;
                }
                ExamApplyDto examApplyDto = commonServiceImpl.getExamApplyInfo(applyNo, null);
                if (!StringUtils.isNotBlank(examApplyDto.getReqMemo())) {
                    continue;
                }
                if (reqMemoList.contains(examApplyDto.getReqMemo())) {
                    continue;
                }
                reqMemoList.add(examApplyDto.getReqMemo());
            }
            if (!CollectionUtils.isEmpty(reqMemoList)) {
                ea.setReqMemo(String.join(",", reqMemoList));
            }
        }
        return JsonResultUtil.success(apply);
    }

    /***
     * 获取和组装预约信息
     * @param dto
     * @param apply
     * @param eais
     * @return
     */
    @Override
    public ExamApplyDto getApplyForScheduleInfo(ExamApplyDto dto, ExamApplyDto apply, List<ExamApplyItemDto> eais) {
        apply.setIndolenceFlag("0");
        apply.setClamFlag("0");
        if (StringUtils.isNotBlank(apply.getFlags())) {
            char[] flagsArr = apply.getFlags().toCharArray();
            apply.setIndolenceFlag(String.valueOf(flagsArr[12]));
            apply.setInfectious(String.valueOf(flagsArr[13]));
            apply.setFilingFlag(String.valueOf(flagsArr[14]));
            apply.setClamFlag(String.valueOf(flagsArr[15]));
            apply.setMultiDrug(String.valueOf(flagsArr[16]));
            apply.setBedside(String.valueOf(flagsArr[8]));
        }
        // 获取申请单预约信息
        commonServiceImpl.getScheduleToExamApply(dto, apply);

        if (StringUtils.isNotBlank(apply.getExamStatus()) || StringUtils.isNotBlank(apply.getScheduleStatus())) {
            apply.setDrugTime("");
            apply.setScheduleStatus(CommonUtil.turnScheduleStatus(apply.getScheduleStatus()));
            apply.setScheduleApm(StringUtils.isNotBlank(apply.getExamApm()) ? apply.getExamApm() : apply.getScheduleApm());
            getExamScheduleInfo(apply, eais.get(0));
        }
        List<String> notices = new ArrayList<String>();
        List<String> itemNotices = new ArrayList<String>();
        List<ExamItemDto> items = new ArrayList<ExamItemDto>();
        double costs = 0.0;
        double charges = 0.0;
        /**
         * 构建申请单检查项目信息
         */
        for (ExamApplyItemDto examApplyItem : eais) {
            ExamItemDto item = new ExamItemDto();
            BeanUtils.copyProperties(examApplyItem, item);
            item.setCode(examApplyItem.getItemCode());
            item.setName(examApplyItem.getItemName());
            item.setPatlocalId(examApplyItem.getPatLocalId());
            item.setMobileNoticeItemDtos(examApplyItem.getMobileNotices());
            items.add(item);

            double cost = (examApplyItem.getCost() == null) ? 0.0 : examApplyItem.getCost();
            double charge = (examApplyItem.getCharge() == null) ? 0.0 : examApplyItem.getCharge();
            costs = BigDecimalUtil.add(costs, cost);
            charges = BigDecimalUtil.add(charges, charge);
            if (StringUtils.isNotBlank(examApplyItem.getNotice())) {
                String[] split = examApplyItem.getNotice().split("\\|");
                for (String n : split) {
                    if (!itemNotices.contains(n)) {
                        itemNotices.add(n);
                    }
                }
            }
            QueryWrapper<ExamApply> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("APPLY_NO", examApplyItem.getApplyNo());
            List<ExamApply> list = examApplyMapper.selectList(queryWrapper);
            String applyNotice = StringUtils.isNotBlank(list.get(0).getNotice()) ? list.get(0).getNotice() : "";
            if (StringUtils.isBlank(applyNotice)) {
                if (StringUtils.isNotBlank(examApplyItem.getNotice())) {
                    notices.add(examApplyItem.getNotice());
                }
            } else {
                notices.add(applyNotice);
            }
        }
        notices = CommonUtil.convertNotice(notices, apply.getPatientSource(), apply.getEndTime(), apply.getBirthDate());
        if (StringUtils.isNotBlank(apply.getReqHospital())) {
            DictHospitalDto dh = new DictHospitalDto();
            dh.setHospitalName(apply.getReqHospital());
            List<DictHospital> hospitals = dictHospitalService.getHospitalListAll(dh);
            if (CollectionUtils.isNotEmpty(hospitals)) {
                apply.setDictScheduleHospital(hospitals.get(0));
                String hospitalName = hospitals.get(0).getHospitalAlias();
                if (StringUtils.isBlank(hospitalName)) {
                    hospitalName = hospitals.get(0).getHospitalName();
                }
                apply.setReqHospital(hospitalName);
                apply.setLongitude("" + hospitals.get(0).getLongitude());
                apply.setLatitude("" + hospitals.get(0).getLatitude());
            }
        }
        apply.setAddress(apply.getMailingAddress());
        apply.setDesc(examScheduleActMapper.getActDesc(dto.getApplyNo()));
        apply.setNotices(notices);
        apply.setItemTaboo(String.join("<br/>", CommonUtil.convertTaboo(itemNotices)));
        apply.setExamItems(items);
        apply.setCosts(costs);
        apply.setCharges(charges);
        if (StringUtils.isNotBlank(apply.getTransTool())) {
            String[] tArr = apply.getTransTool().split("\\|");
            apply.setTransTool(tArr[0]);
            if (tArr.length > 1) {
                apply.setSendBack(tArr[1]);
            }
        }
        String lastMensesDateStr = apply.getLastMensesDate();
        apply.setGestational("0");
        apply.setLastMensesDate("");
        if (apply.getSex() != null && apply.getSex().contains(ConstantsUtil.Gender.WOMAN.getValue()) && commonServiceImpl.isGestationalApply(eais)) {
            String isGestational = "1";
            if (StringUtils.isBlank(lastMensesDateStr)) {
                lastMensesDateStr = commonServiceImpl.getLastMensesDate(apply.getSickId());
            }
            if (StringUtils.isNotBlank(lastMensesDateStr)) {
                Date nowDate = DateUtil.getNow();
                Date lastMensesDate = DateUtil.parse(lastMensesDateStr, DateUtil.FORMAT_DATE);
                int allDays = (int) ((nowDate.getTime() - lastMensesDate.getTime()) / 86400000L);
                int weeks = allDays / 7;
                if (weeks < 50) {
                    isGestational = "2";
                }
            }
            apply.setGestational(isGestational);
            apply.setLastMensesDate(lastMensesDateStr);
        }
        String isScheduleHint = commonServiceImpl.isScheduleByFlags(eais, dto.getTerminalType(), apply.getChargeType());
        apply.setOnlyDeptscheScheduleHint(isScheduleHint);
        if (StringUtils.isNotBlank(apply.getExamClass()) && (StringUtils.isNotBlank(apply.getZoneName()) || StringUtils.isNotBlank(apply.getSignZoneName()))) {
            String zoneName = apply.getSignZoneName();
            boolean isSchedule = true;
            if (StringUtils.isNotBlank(apply.getZoneName()) && StringUtils.isNotBlank(apply.getExamStatus()) && Integer.parseInt(apply.getExamStatus()) >= 10) {
                isSchedule = false;
                zoneName = apply.getZoneName();
            }
            DictExamZoneDto dictExamZoneDto = new DictExamZoneDto();
            dictExamZoneDto.setExamClass(apply.getExamClass());
            dictExamZoneDto.setZoneName(zoneName);
            List<DictExamZone> examZoneList = dictExamZoneService.getList(dictExamZoneDto);
            if (examZoneList != null && !examZoneList.isEmpty() && StringUtils.isNotBlank(examZoneList.get(0).getLocation())) {
                if (isSchedule) {
                    apply.setSignLocation(examZoneList.get(0).getLocation());
                } else {
                    apply.setLocation(examZoneList.get(0).getLocation());
                }
            }
        }
        return apply;
    }


    private void getExamScheduleInfo(ExamApplyDto apply, ExamApplyItemDto itemDto) {
        apply.setExamQueueName(itemDto.getExamQueueName());
        apply.setQueueNo(itemDto.getQueueNo());
        apply.setPatLocalId(itemDto.getPatLocalId());
        if (StringUtils.isNotBlank(apply.getScheduleApm())) {
            Map<String, Object> apmMap = new HashMap<String, Object>();
            apmMap.put("APM_CODE", apply.getApmCode());
            QueryWrapper<DictScheduleApm> dsaQw = new QueryWrapper<>();
            dsaQw.allEq(apmMap);
            DictScheduleApm dsa = dictScheduleApmMapper.selectOne(dsaQw);
            if (dsa != null) {
                String timeEarliest = StringUtils.isBlank(dsa.getTimeEarliest()) ? dsa.getTimeStart().substring(0, dsa.getTimeStart().length() - 3) : dsa.getTimeEarliest().substring(0, dsa.getTimeEarliest().length() - 3);
                String timeSignin = StringUtils.isBlank(dsa.getTimeSignin()) ? "" : dsa.getTimeSignin().substring(0, dsa.getTimeSignin().length() - 3);
                String advanceTime = "";
                String dateTimeSignEarliest = apply.getScheduleDate() + " " + timeEarliest;
                if (Objects.nonNull(dsa.getDaysEarliest()) && !"0".equals(dsa.getDaysEarliest())) {
                    String dateEarliest = DateUtil.addDays2(apply.getScheduleDate(), -dsa.getDaysEarliest());
                    dateTimeSignEarliest = dateEarliest + " " + timeEarliest;
                    advanceTime = dateEarliest + " " + timeEarliest;
                } else if (StringUtils.isNotBlank(timeEarliest)) {
                    advanceTime = apply.getScheduleDate() + " " + timeEarliest;
                } else {
                    advanceTime = apply.getScheduleDate() + " " + apply.getScheduleApm().replaceAll("~", "-").split("-")[0] + ":00";
                }
                apply.setAdvanceTime(advanceTime);
                apply.setDateTimeSignEarliest(dateTimeSignEarliest);
                String reqReqchTime = "";
                String dateTimeSignLatest = apply.getScheduleDate() + " " + timeSignin;
                if (StringUtils.isNotBlank(dsa.getDaysSignin()) && !"0".equals(dsa.getDaysSignin())) {
                    String dateSignLatest = DateUtil.addDays2(apply.getScheduleDate(), -Integer.parseInt(dsa.getDaysSignin()));
                    dateTimeSignLatest = dateSignLatest + " " + timeSignin;
                    reqReqchTime = dateSignLatest + " " + timeSignin;
                } else if (StringUtils.isNotBlank(apply.getReqReachTime())) {
                    reqReqchTime = apply.getScheduleDate() + " " + apply.getReqReachTime();
                } else if (StringUtils.isNotBlank(timeSignin)) {
                    reqReqchTime = apply.getScheduleDate() + " " + timeSignin;
                } else {
                    reqReqchTime = apply.getScheduleDate() + " " + apply.getScheduleApm().replaceAll("~", "-").split("-")[1] + ":00";
                }
                apply.setReqReachTime(reqReqchTime);
                apply.setDateTimeSignLatest(dateTimeSignLatest);
                String endTime = DateUtil.addSecond(dsa.getTimeEnd(), 1);
                endTime = endTime.substring(0, dsa.getTimeEnd().length() - 3);
                apply.setEndTime(endTime);
                String startTime = dsa.getTimeStart().substring(0, dsa.getTimeStart().length() - 3);
                apply.setStartTime(startTime);
                apply.setTimeEarliest(timeEarliest);
                apply.setTimeSignin(timeSignin);
            }
        }
    }

    @Override
    public List<String> getReminders(String type, String examClass, String terminalType) {
        String reserve1 = "DEFAULT";
        if (ConstantsUtil.TerminalType.DEPT.getType().equals(terminalType)) {
            reserve1 = "CLINIC";
        } else if (ConstantsUtil.TerminalType.CLINIC_IN.getType().equals(terminalType)) {
            reserve1 = "CLINIC";
        } else if (ConstantsUtil.TerminalType.CLINIC_OUT.getType().equals(terminalType)) {
            reserve1 = "CLINIC";
        } else if (ConstantsUtil.TerminalType.SELF.getType().equals(terminalType)) {
            reserve1 = "SELF";
        } else if (ConstantsUtil.TerminalType.MOBILE.getType().equals(terminalType)) {
            reserve1 = "MOBILE";
        } else if (ConstantsUtil.TerminalType.SCHEDULE_CENTER.getType().equals(terminalType)) {
            reserve1 = "CLINIC";
        } else if (ConstantsUtil.TerminalType.SCHEDULE_MANAGE.getType().equals(terminalType)) {
            reserve1 = "CLINIC";
        }
        List<String> reminders = new ArrayList<>();
        List<DictCommonUse> list = commonServiceImpl.findReminderList(type, examClass, reserve1);
        if (list == null || list.size() == 0) {
            reserve1 = "DEFAULT";
            list = commonServiceImpl.findReminderList(type, examClass, reserve1);
        }
        if (list != null && list.size() > 0) {
            for (int i = 0; i < list.size(); ++i) {
                reminders.add(i + 1 + "." + list.get(i).getValue());
            }
        }
        return reminders;
    }


//    public JsonResult getPatientListOut(ExamApplyDto dto) {
//        configServiceImpl.toUpperCaseInput(dto);
//
////        dto.setCommonCard(configServiceImpl.getCommonCardConfig(dto.getCommonCard()));
////        JsonResult virtualCardResult = commonServiceImpl.commonCard2VirtualCardReader(dto);
////        if (virtualCardResult != null && "1".equals(virtualCardResult.getStatus()))
////            return virtualCardResult;
//        dto.setExamClasses(CommonUtil.split2List(dto.getExamClass()));
//        dto.setPatientSources(CommonUtil.split2List(dto.getPatientSource()));
//        dto.setApplyNos(CommonUtil.split2List(dto.getApplyNo()));
//        dto.setPriorityOrders(CommonUtil.split2List(dto.getPriorityOrder()));
//        dto.setPriorityOrder(null);
//        dto.setReqWardCodes(CommonUtil.split2List(dto.getReqWardCode()));
//        dto.setReqWardCode(null);
//        dto.setReqDepts(CommonUtil.split2List(dto.getDeptCode()));
//        dto.setPerformDepts(CommonUtil.split2List(dto.getPerformDept()));
//        dto.setPerformDept(null);
//        dto.setItemFlags(CommonUtil.convertItemFlagsCondition(dto.getItemFlags()));
//        dto.setScheduleStatus(CommonUtil.convertScheduleStatus(dto.getScheduleStatus()));
//        if (StringUtils.isNotBlank(dto.getItemStatus()))
//            dto.setScheduleStatus(CommonUtil.convertScheduleStatus(dto.getItemStatus()));
//        dto.setIncludeFlags(CommonUtil.convertFlagsCondition(dto.getIncludeFlags()));
//        List<String> excludeFlagsList = new ArrayList<>();
//        List<String> flagList = CommonUtil.split2List(dto.getExcludeFlags());
//        for (String flag : flagList)
//            excludeFlagsList.add(CommonUtil.convertFlagsCondition(flag));
//        dto.setExcludeFlagsList(excludeFlagsList);
//        dto.setExcludeFlags(null);
//        if (StringUtils.isNotBlank(dto.getIcCard2()) ||
//                StringUtils.isNotBlank(dto.getIcCard()) ||
//                StringUtils.isNotBlank(dto.getSickId()) ||
//                StringUtils.isNotBlank(dto.getOutpatientNo()) ||
//                StringUtils.isNotBlank(dto.getApplyNo()) ||
//                StringUtils.isNotBlank(dto.getCommonCard())) {
//            JsonResult jsonResult = commonServiceImpl.getHisApply(dto);
//        }
//
//        int pageNo = 1;
//        int pageSize = 100;
//        List<String> sickIdList = configServiceImpl.getInputNewSupport(dto);
//        dto.setSickIds(sickIdList);
//        PageHelper.startPage(pageNo, pageSize);
//        List<ExamApplyDto> list = examApplyMapper.getPatientListOut(dto);
//        List<String> sickList = new ArrayList<>();
//        for (ExamApplyDto ead : list)
//            sickList.add(ead.getSickId());
//        List<ExamApplyDto> lsExamApplyDto = new ArrayList<>();
//        Map<String, String> scheduleStatusMap = new HashMap<>();
//        HashSet<String> hs = new HashSet<>();
//        for (ExamApplyDto ea : list) {
//            String sickName = ea.getSickId() + ea.getName();
//            String scheduleStatus = (ea.getExamStatus() != null) ? ea.getExamStatus() : ea.getScheduleStatus();
//            if (ConstantsUtil.ScheduleStatus.ONE.getStatus().equals(scheduleStatus))
//                scheduleStatus = null;
//            if (!scheduleStatusMap.containsKey(sickName) && StringUtils.isBlank(scheduleStatus))
//                scheduleStatusMap.put(sickName, ConstantsUtil.ScheduleStatus.ZERO.getStatus());
//            if (hs.contains(sickName))
//                continue;
//            hs.add(sickName);
//            lsExamApplyDto.add(ea);
//        }
//        for (ExamApplyDto ead : lsExamApplyDto) {
//            String sickName = ead.getSickId() + ead.getName();
//            if (scheduleStatusMap.containsKey(sickName)) {
//                ead.setScheduleStatus("0");
//                continue;
//            }
//            ead.setScheduleStatus("1");
//        }
//        return JsonResultUtil.success(lsExamApplyDto);
//    }
}
